package com.study.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.study.system.common.result.Result;
import com.study.system.model.dto.FileInfo;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;

@Tag(name = "07.文件接口")
@RestController
@RequestMapping("/api/v1/files")
@RequiredArgsConstructor
public class FileController {



    @SneakyThrows
    @PostMapping
    @Operation(summary = "文件上传", security = {@SecurityRequirement(name = "Authorization")})
    public Result<FileInfo> uploadFile(
            @Parameter(description ="表单文件对象") @RequestParam(value = "file") MultipartFile file
    ) {
        // 生成文件名(日期文件夹)
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        // 前缀
        String test = "file";
        String uuid = IdUtil.simpleUUID();
        String fileName = DateUtil.format(LocalDateTime.now(), "yyyy/MM/dd") + "/" + uuid + "." + suffix;
        // 获取文件访问路径
        boolean exist = FileUtil.exist("D:\\bigsmart\\" + test + "\\" + DateUtil.format(LocalDateTime.now(), "yyyy/MM/dd"));
        if (!exist){
            FileUtil.mkdir("D:\\bigsmart\\" + test + "\\" + DateUtil.format(LocalDateTime.now(), "yyyy/MM/dd"));
        }
        file.transferTo(new File("D:\\bigsmart\\" + test  + "\\" + fileName));
        String fileUrl = "http://localhost:8989/file/" + fileName;
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(fileName);
        fileInfo.setUrl(fileUrl);

        return Result.success(fileInfo);
    }


}
